package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.pojo.PaperQuestion;
import com.hqyj.dao.PaperQuestionDao;
import com.hqyj.pojo.R;
import com.hqyj.service.PaperQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2022-10-25 02:24:43
 */
@Service
public class PaperQuestionServiceImpl extends ServiceImpl<PaperQuestionDao, PaperQuestion> implements PaperQuestionService {

    // 1 Resource 和  Autowired 区别
    // 答：一：Resource 是java原生注解 ，Autowired 是spring的注解
    //二：Resource是按名称(byName)自动装配
    //三：Autowired是按类型(byType)自动装配
    //注入Dao
    @Resource
    PaperQuestionDao paperQuestionDao;


    @Override
    public R query(PaperQuestion paperQuestion) {
        //1 创建分页对象
        Page<PaperQuestion> questionPage = new Page<>(paperQuestion.getPage(),paperQuestion.getRow());
        //创建条件构造器
        QueryWrapper<PaperQuestion> queryWrapper = new QueryWrapper<>();
        //题目的模糊查询
        boolean is = paperQuestion.getQuContent()!=null&&!paperQuestion.getQuContent().equals("");
        queryWrapper.like(is,"qu_content",paperQuestion.getQuContent());

        //题型的精确查询
        boolean iss = paperQuestion.getQuType()!=null&&!paperQuestion.getQuType().equals("");
        queryWrapper.eq(iss,"qu_type",paperQuestion.getQuType());

        //2 获取查询结果
        Page<PaperQuestion> pageList=paperQuestionDao.selectPage(questionPage,queryWrapper);

        if(pageList.getRecords().size()>0){
            Map<String,Object> map = new HashMap<>();
            //当前页集合
            map.put("list",pageList.getRecords());
            //总条数
            map.put("total",pageList.getTotal());
            //总页数
            map.put("totalPage",pageList.getPages());

            return R.ok(map);
        }
        return R.error();
    }

    @Override
    public R add(PaperQuestion paperQuestion) throws ParseException {
        //插入系统当前时间为创建时间
        paperQuestion.setCreateTime(null);
        int num = paperQuestionDao.insert(paperQuestion);
        if(num >0 ){
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R del(String id) {
        int num = paperQuestionDao.deleteById(id);
        if(num >0 ){
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R update(PaperQuestion paperQuestion) {
        int num = paperQuestionDao.updateById(paperQuestion);
        if(num >0 ){
            return R.ok();
        }
        return R.error();
    }
}
